namespace IAM.Interface.Common.Context
{
    using IAM.Interface.Common;
    using IAM.Interface.Common.Abnormity;
    using IAM.Interface.Common.Encrypt;
    using IAM.Interface.Common.XMLResolution;
    using IAM.Interface.DAL.Response;
    using IAM.Interface.Model;
    using IAM.Interface.Model.ENUM;
    using IAM.Interface.Model.Interface;
    using System;
    using System.Configuration;
    using System.Web;
    using System.Xml;

    public class ResponseContextControl
    {
        private ResponseContextModel _contextmodel;
        private IAM.Interface.Common.Abnormity.ResponseException _re;
        private IAM.Interface.Common.XMLResolution.Request _request;
        private string _xml;

        public ResponseContextControl()
        {
            this._contextmodel = null;
            this._xml = "";
            this._request = null;
            this._re = null;
        }

        public ResponseContextControl(ResponseContextModel contextmodel)
        {
            this._contextmodel = null;
            this._xml = "";
            this._request = null;
            this._re = null;
            this._contextmodel = contextmodel;
        }

        public string ContextControl()
        {
            object inceptobj = null;
            try
            {
                inceptobj = this.Incept();
            }
            catch (IAM.Interface.Common.Abnormity.ResponseException re)
            {
                this.ResponseException = re;
                return this.Send(new NullityObj(), new IAM.Interface.Common.XMLResolution.Request(), this.ResponseException);
            }
            catch (Exception ex)
            {
                this.ResponseException = new IAM.Interface.Common.Abnormity.ResponseException();
                this.ResponseException.SetStateMessage(500, ex.Message);
                return this.Send(new NullityObj(), new IAM.Interface.Common.XMLResolution.Request(), this.ResponseException);
            }
            object resultobj = this.TransferBLL(inceptobj, this.Request);
            return this.Send((IConvertXml) resultobj, this.Request, this.ResponseException);
        }

        public static string GetConfigKey()
        {
            string key = ConfigurationManager.AppSettings["IAM_Key"];
            EncryptDecrypt ed = new EncryptDecrypt();
            ed.Key = ed.GenerateKey();
            return ed.Decrypt(key);
        }

        private object Incept()
        {
            EncryptDecrypt endecrypt = new EncryptDecrypt();
            endecrypt.Key = this.ContextModel.Key;
            this.XML = endecrypt.Decrypt(this.ContextModel.XML);
            if (!this.ValidateSign(this.XML))
            {
                throw new IAM.Interface.Common.Abnormity.ResponseException(700);
            }
            XmlDocument _xmldocumenttemp = new XmlDocument();
            _xmldocumenttemp.LoadXml(this.XML);
            if (!this.ValidateOvertime(Convert.ToDateTime(_xmldocumenttemp.DocumentElement.Attributes["RequestTime"].Value)))
            {
                throw new IAM.Interface.Common.Abnormity.ResponseException(710);
            }
            if (!this.ValidateGuid(_xmldocumenttemp.DocumentElement.Attributes["TransactionID"].Value))
            {
                throw new IAM.Interface.Common.Abnormity.ResponseException(800);
            }
            IAM.Interface.Common.XMLResolution.Request request = new IAM.Interface.Common.XMLResolution.Request();
            request.XmlDocument = new XmlDocument();
            request.XmlInfo = this.XML;
            request.XmlDocument.LoadXml(request.XmlInfo);
            this.Request = request;
            XmlObjConversion xoc = new XmlObjConversion(request.GetActionType(), request.XmlDocument.DocumentElement.Name);
            xoc.CurrentXmlNode = request.GetCurrentNode();
            return xoc.ConvertToObj();
        }

        private string Send(IConvertXml obj, IAM.Interface.Common.XMLResolution.Request request, IAM.Interface.Common.Abnormity.ResponseException exception)
        {
            string xml = "";
            xml = new XmlObjConversion(obj).GetXml();
            AbstractXMLResolution abxmlresolution = new Response(request.GetActionType(), exception, request.GetTransactionID());
            abxmlresolution.XmlInfo = xml;
            xml = abxmlresolution.GetWholeXML();
            EncryptDecrypt endecrypt = new EncryptDecrypt();
            endecrypt.Key = this.ContextModel.Key;
            return endecrypt.Encrypt(xml);
        }

        private object TransferBLL(object obj, IAM.Interface.Common.XMLResolution.Request request)
        {
            object returnobj = null;
            IdentityMgnt businessIM = null;
            ACIMgnt businessACIMgnt = null;
            DelegationMgnt busnessDM = null;
            try
            {
                this.ResponseException = new IAM.Interface.Common.Abnormity.ResponseException();
                switch (request.GetActionType())
                {
                    case ActionType.IDEN_MANAGE:
                        businessIM = new IdentityMgnt();
                        switch (request.GetOperationType())
                        {
                            case OperationType.Create:
                                return businessIM.CreateIdentity((Identity) obj);

                            case OperationType.Enable:
                                return businessIM.EnableIdentity((Identity) obj);

                            case OperationType.Disable:
                                return businessIM.DisableIdentity((Identity) obj);

                            case OperationType.Delete:
                                return businessIM.DeleteIdentity((Identity) obj);

                            case OperationType.Update:
                                return businessIM.UpdateIdentity((Identity) obj);
                        }
                        return returnobj;

                    case ActionType.IDEN_GETACMODEL:
                        businessACIMgnt = new ACIMgnt();
                        return businessACIMgnt.GetACIModel();

                    case ActionType.IDEN_GETUSERACI:
                        businessACIMgnt = new ACIMgnt();
                        return businessACIMgnt.GetUserACI((AccountInfo) obj);

                    case ActionType.IDEN_SETUSERACI:
                        businessACIMgnt = new ACIMgnt();
                        return businessACIMgnt.SetUserACI((ACI) obj);

                    case ActionType.ORG_UPDATE:
                        returnobj = new OrganizationMgnt().UpdateOrganize((OrganizeInfo) obj);
                        if ((bool) returnobj)
                        {
                            return new NullityObj();
                        }
                        return new NullityObj();

                    case ActionType.ORG_CREATE:
                        returnobj = new OrganizationMgnt().CreateOrganize((OrganizeInfo) obj);
                        if ((bool) returnobj)
                        {
                            return new NullityObj();
                        }
                        return new NullityObj();

                    case ActionType.ORG_DELETE:
                        returnobj = new OrganizationMgnt().DeleteOrganize((OrganizeDeleteParameter) obj);
                        if ((bool) returnobj)
                        {
                            break;
                        }
                        return new NullityObj();

                    case ActionType.DM_GETMODULELIST:
                        busnessDM = new DelegationMgnt();
                        return busnessDM.GetModuleList();

                    case ActionType.DM_GETDELEINFO:
                        busnessDM = new DelegationMgnt();
                        return busnessDM.GetDelegationInfo((AccountInfo) obj);

                    case ActionType.DM_SETDELEINFO:
                        busnessDM = new DelegationMgnt();
                        return busnessDM.SetDelegationInfo((AIDelegations) obj);

                    default:
                        return returnobj;
                }
                returnobj = new NullityObj();
            }
            catch (IAM.Interface.Common.Abnormity.ResponseException re)
            {
                this.ResponseException = re;
                return new NullityObj();
            }
            catch (Exception ex)
            {
                this.ResponseException.SetStateMessage(500, ex.Message);
                return new NullityObj();
            }
            return returnobj;
        }

        private bool ValidateGuid(string requestguid)
        {
            return true;
        }

        private bool ValidateOvertime(DateTime requesttime)
        {
            if (Math.Abs(DateTime.Now.Subtract(requesttime).TotalMinutes) > 5.0)
            {
                return false;
            }
            return true;
        }

        public bool ValidateRequestIP()
        {
            string requesttip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
            string directory = AppDomain.CurrentDomain.BaseDirectory;
            if ((directory.Substring(directory.Length - 1) != "/") && !(directory.Substring(directory.Length - 1) == @"\"))
            {
                directory = directory + @"\";
            }
            string appsfilename = directory + "RequestIPs.xml";
            XmlDocument xd = new XmlDocument();
            xd.Load(appsfilename);
            XmlNodeList xnl = xd.SelectNodes("//RequestIP");
            foreach (XmlNode xnoneofips in xnl)
            {
                if (xnoneofips.InnerText.ToLower().Trim() == requesttip.ToLower().Trim())
                {
                    return true;
                }
            }
            return false;
        }

        public bool ValidateSign(string xml)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xml);
            string signatureValue = new XMlSign().SignXml(xmlDoc);
            EncryptDecrypt endecrypt = new EncryptDecrypt();
            endecrypt.Key = this.ContextModel.Key;
            return (endecrypt.Encrypt(signatureValue).Trim() == this.ContextModel.Sign.Trim());
        }

        public ResponseContextModel ContextModel
        {
            get
            {
                return this._contextmodel;
            }
            set
            {
                this._contextmodel = value;
            }
        }

        public IAM.Interface.Common.XMLResolution.Request Request
        {
            get
            {
                return this._request;
            }
            set
            {
                this._request = value;
            }
        }

        public IAM.Interface.Common.Abnormity.ResponseException ResponseException
        {
            get
            {
                return this._re;
            }
            set
            {
                this._re = value;
            }
        }

        public string XML
        {
            get
            {
                return this._xml;
            }
            set
            {
                this._xml = value;
            }
        }
    }
}
